<?php
namespace Helper\Controller;
use Think\Controller;
class DownloadController extends Controller {
    //文件下载
    function index() {
        header("Content-type:text/html;charset=utf-8");
        $file_path = I('file_path');
        $file_name = I('file_name');

        if (!$file_path) {
            $this->error('文件路径不存在');
        }

        //首先要判断给定的文件存在与否
        $file_size = '';
        if (!file_exists($file_path)) {
            $file_path  = x_get_file_download_url($file_path);
            $file_exist = @file_get_contents($file_path, null, null, -1, 1) ? true : false;
            if (!$file_exist) {
                $this->error('存储文件不存在或者无权限访问');
            }
            $info = get_headers($file_path, true);
            $file_size = $info['Content-Length'];
        }

        $fp = fopen($file_path, 'r');
        $file_size = $file_size ? : filesize($file_path);
        //下载文件需要用到的头
        Header("Content-type: application/octet-stream");
        Header("Accept-Ranges: bytes");
        Header("Accept-Length:" . $file_size);
        Header("Content-Disposition: attachment; filename=" . $file_name);
        $buffer     = 1024;
        $file_count = 0;
        //向浏览器返回数据
        while (!feof($fp) && $file_count < $file_size) {
            $file_con    =   fread($fp, $buffer);
            $file_count += $buffer;
            echo $file_con;
        }
        fclose($fp);
    }
}
